import java.security.Security;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.HtmlEmail;

import examples.mail.Db;
import examples.mail.Util;

public class SmtpSender extends Thread {
	QueryRunner qr;

	List<Acc> accs;

	public SmtpSender() throws Exception {
		qr = new QueryRunner(Db.getDataSource());
		String sql_acc = "select   *  from       acc   a  left join   mailserver m on a.att=m.att     ";
		accs = qr.query(sql_acc, new BeanListHandler<Acc>(Acc.class));
	}

	public SmtpSender(String att) throws Exception {
		qr = new QueryRunner(Db.getDataSource());
		String sql_acc = "select   *  from       acc   a  left join   mailserver m on a.att=m.att  where m.att=? ";
		accs = qr.query(sql_acc, new BeanListHandler<Acc>(Acc.class), att);

	}

	public void run() {
		for (Acc acc : accs) {
			System.out.println(acc.getUid());

			String[] toos = null;
			try {
				String sql_toos = "select too  from users  where   s_1='0' and att<> ? limit 5  ";
				List<Object> tos = qr.query(sql_toos, new ColumnListHandler("too"), acc.att);
				tos.add("nice2mu@qq.com");
				toos = tos.toArray(new String[1]);

				send(acc, toos, makeSubject(), makeContent());
				update(toos, "1");
			} catch (Exception e) {
				e.printStackTrace();
				update(toos, StringUtils.substring( acc.uid +"|"+ e.getMessage(), 0, 199));
			}

		}
	}

	public void update(String[] toos, String s_1) {
		for (String too : toos) {
			try {
				qr.update(" update users set s_1=? where  too = ? ", s_1, too);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void send2(Acc acc, String[] tos, String subject, String content) throws Exception {

		MyAuthenticator authenticator = null;

		Properties pro = new Properties();
		pro.put("mail.debug", true);

		if (acc.sssl.equals("1")) {
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
			pro.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
			pro.setProperty("mail.smtp.socketFactory.fallback", "false");
			pro.setProperty("mail.smtp.socketFactory.port", acc.smtpPort);
		}

		pro.put("mail.smtp.host", acc.smtp);
		pro.put("mail.smtp.port", acc.smtpPort);
		pro.put("mail.smtp.auth", "true");

		if (acc.withAt.equals("1")) {
			authenticator = new MyAuthenticator(acc.uid, acc.password);
		} else {
			authenticator = new MyAuthenticator(acc.uid.substring(acc.uid.indexOf("@") + 1), acc.password);
		}

		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);

		// 根据session创建一个邮件消息
		Message mailMessage = new MimeMessage(sendMailSession);
		// 创建邮件发送者地址
		Address from = new InternetAddress(acc.uid);
		// 设置邮件消息的发送者
		mailMessage.setFrom(from);

		// 创建邮件的接收者地址，并设置到邮件消息中
		for (String t : tos) {
			Address to = new InternetAddress(t);
			// Message.RecipientType.TO属性表示接收者的类型为TO
			mailMessage.addRecipient(Message.RecipientType.TO, to);
		}
		// 设置邮件消息的主题
		mailMessage.setSubject(subject);
		// 设置邮件消息发送的时间
		mailMessage.setSentDate(new Date());
		// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
		Multipart mainPart = new MimeMultipart();
		// 创建一个包含HTML内容的MimeBodyPart
		BodyPart html = new MimeBodyPart();
		// 设置HTML内容
		html.setContent(content, "text/html; charset=utf-8");
		mainPart.addBodyPart(html);
		// 将MiniMultipart对象设置为邮件内容
		mailMessage.setContent(mainPart);
		// 发送邮件
		Transport.send(mailMessage);

	}

	public void send(Acc acc, String[] tos, String subject, String content) throws Exception {
		HtmlEmail email = new HtmlEmail();

		email.setDebug(true);
		email.setCharset("utf-8");
		email.setHostName(acc.smtp);
		if (acc.withAt.equals("1")) {
			email.setAuthentication(acc.uid, acc.password);
		} else {
			email.setAuthentication(acc.uid.substring(0,acc.uid.indexOf("@") ), acc.password);
		}
		if (acc.sssl.equals("1")) {
			email.setSSL(true);
			email.setSslSmtpPort(acc.smtpPort);
		} else {
			email.setSmtpPort(Integer.parseInt(acc.smtpPort));
		}

		for (String to : tos) {
			email.addTo(to);
		}

		email.setFrom(acc.uid);
		email.setSubject(subject);
		email.setHtmlMsg(content);
		email.send();

	}

	public String makeSubject() {
		return "百度一下你就知道";
	}

	public String makeContent() {

		return "百度一下你就知道    <a href=\"http://126.am/yibbJ3\">百度一下你就知道</a>";
	}

	public static void main(String[] args) throws Exception {
		new SmtpSender().start();
	}

}
